package com.example.sid.ui.fragments.app_token

import android.graphics.Color
import android.widget.EditText
import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.example.sid.R
import com.example.sid.data.ValueRamStorage
import com.example.sid.how_to_use.AsyncSIDFacade
import kotlinx.coroutines.launch

/**
 * Тут мы задаём настройки для открытия браузера с возможностью авторизации у партнёра
 */
class GoToPartnerSSOFragment : Fragment(R.layout.fragment_go_to_partner_sso) {

	private val appTokenRadioGroupBrowser: RadioGroup?
		get() = view?.findViewById(R.id.app_token_radio_group_browser)

	private val webLink: EditText get() = requireView().findViewById(R.id.webLink)
	private val clientId: EditText get() = requireView().findViewById(R.id.clientId)
	private val partnerColorInt: EditText get() = requireView().findViewById(R.id.partnerColorInt)

	private var appTokenRadio:String? = "webview"
	override fun onStart() {
		super.onStart()
		appTokenRadioGroupBrowser?.setOnCheckedChangeListener { group, checkedId ->
			appTokenRadio = when(checkedId){
				R.id.app_token_radio_browser -> "browser"
				R.id.app_token_radio_webview -> "webview"
				R.id.app_token_radio_none -> null
				else -> null
			}
		}

		clientId.setText(ValueRamStorage.partnerID)

		lifecycleScope.launch {
			AsyncSIDFacade.goToPartnerSSO(
				activity = requireActivity(),
				webLink = webLink.toString(),
				clientId = clientId.toString(),
				partnerColorInt = kotlin.runCatching { Color.parseColor(partnerColorInt.toString()) }.getOrNull() ?: Color.GREEN,
				openIn = appTokenRadio
			)
		}

	}
}